import { memo, useCallback, useEffect, DragEvent, useState, useRef } from "react";
import { NodeResizeControl, Position, useReactFlow, Node, CoordinateExtent } from "@xyflow/react";
import { Card, Form, Modal, Spin } from "antd";
import useSelectBorder from "../../store/useSceneData";
import Subtitle from "../../components/Subtitle";
import { useDnD } from "../../context/DnDContext";
import NodeOperation from "../../components/NodeOperation";
import CustomHandle from "../CustomHandle";
import { debounceTime } from "../../utils/utils";
import LlmSelect from "../../components/LlmSelect";
import { Loading3QuartersOutlined } from "@ant-design/icons";


interface NodeType extends Node {
    type: string
}

const asyncTime = debounceTime(500)

/**
 * 提示词模版
 * @param param0
 * @returns
 */
function IterationNode({ id, data }: Node) {
    const { select, setSelectId, debug } = useSelectBorder()
    const { setNodes, setCenter, screenToFlowPosition, getViewport } = useReactFlow();
    const [type] = useDnD();
    const cardRef = useRef<HTMLDivElement>(null)
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [form] = Form.useForm();


    const handleDrop = useCallback(
        (event: DragEvent<HTMLDivElement>) => {
            event.preventDefault();
            event.stopPropagation();

            if (!type) {
                return;
            }

            const { x, y } = cardRef.current.getBoundingClientRect()
            const view = getViewport()

            const extent = viewZoom()
            const newNode: NodeType = {
                id: `id_${Math.random().toString(36).slice(2, 9)}`,
                type,
                position: {
                    x: (event.clientX - x - 50) / view.zoom,
                    y: (event.clientY - y - 50) / view.zoom,
                },
                parentId: id,
                extent: extent,
                data: { label: `${type} node` },
            };

            setNodes((nds) => nds.concat(newNode));
        },
        [screenToFlowPosition, type]
    );

    // 在组件内添加处理函数
    const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
        e.preventDefault(); // 防止默认行为
        e.stopPropagation();
    };

    useEffect(() => {
        if (select[id] && debug) {
            setNodes((nodes: Node[]) => {
                const node = nodes.find(node => node.id == id)
                setCenter(node.position.x + 200, node.position.y, { zoom: 1, duration: 500 })
                return [...nodes];
            })
        }
    }, [select[id]])


    const controlStyle = {
        background: 'transparent',
        border: 'none',
    };

    const viewZoom = () => {
        const { height, width } = cardRef.current.getBoundingClientRect()
        const view = getViewport()
        const positionZoom: CoordinateExtent = [[28, 80], [width / view.zoom - 30, height / view.zoom - 26]]

        setNodes((nodes: Node[]) => {
            nodes.forEach(node => {
                if (node.parentId) {
                    node.extent = positionZoom
                }
            })
            return [...nodes];
        })

        return positionZoom
    }

    return (
        <NodeOperation nodeId={id} onClick={() => setIsModalOpen(true)}>
            <Card
                title={<div className='flex'>
                    <Subtitle imgUrl='img/iteration.png' title={data.title as string || '循环运行'} id={id} />
                    {select[id] && debug && <Spin indicator={<Loading3QuartersOutlined spin />} className='mt-[6px] ml-2' />}
                </div>}
                ref={cardRef}
                style={{
                    outline: select[id] ? "2px solid #145FF0" : "none",
                    height: '100%',
                    minWidth: 400,
                    minHeight: 300,
                    position: 'relative',
                }}
                onClick={() => setSelectId(id)}
                onDragOver={handleDragOver}
                onDrop={handleDrop}
                tabIndex={0}
            >
                <div className="bg-[#F4F4F7] h-[calc(100%-74px)] w-[calc(100%-20px)] absolute rounded-xl translate-x-[-14px] translate-y-[-14px]" />
            </Card>

            <NodeResizeControl style={controlStyle} minWidth={400} minHeight={300}
                onResize={() => {
                    asyncTime(() => viewZoom())
                }}>
                <ResizeIcon />
            </NodeResizeControl>


            <CustomHandle count={1} type="source" position={Position.Right} id="iterationStart" style={{ top: 74 }} />
            <CustomHandle count={1} type="target" position={Position.Left} id="iterationEnd" style={{ top: 74 }} />
        </NodeOperation>
    );
}

function ResizeIcon() {
    return (
        <svg
            xmlns="http://www.w3.org/2000/svg"
            width="20"
            height="20"
            viewBox="0 0 24 24"
            strokeWidth="2"
            stroke="#145FF0"
            fill="none"
            strokeLinecap="round"
            strokeLinejoin="round"
            style={{ position: 'absolute', right: 5, bottom: 5 }}
        >
            <path stroke="none" d="M0 0h24v24H0z" fill="none" />
            <polyline points="16 20 20 20 20 16" />
            <line x1="14" y1="14" x2="20" y2="20" />
            <polyline points="8 4 4 4 4 8" />
            <line x1="4" y1="4" x2="10" y2="10" />
        </svg>
    );
}

export default memo(IterationNode);
